# Time: 2021/6/22 13:36
# Author: 阿尔法
# File: 七夕情话网爬虫-脱单神器.py
# @Software: PyCharm
from threading import Thread
import tkinter as tk
import tkinter.messagebox as msgbox
from requests_html import HTMLSession
import random, time
session = HTMLSession()


class TKSpider(object):

    def __init__(self):
        """定义可视化窗口，并设置窗口和主题大小布局"""
        self.window = tk.Tk()
        self.window.title('阿尔法情话采集-七夕')
        self.window.geometry('800x600')

        """创建label_user按钮，与说明书"""
        self.label_user = tk.Label(self.window, text='请输入情话检索词编号：', font=('Arial', 12), width=30, height=2)
        self.label_user.pack()
        """创建label_user关联输入"""
        self.entry_user = tk.Entry(self.window, show=None, font=('Arial', 14))
        self.entry_user.pack(after=self.label_user)

        """创建Text富文本框，用于按钮操作结果的展示"""
        # 定义富文本框滑动条
        scroll = tk.Scrollbar()
        # 放到窗口的右侧, 填充Y竖直方向
        scroll.pack(side=tk.RIGHT, fill=tk.Y)
        self.text1 = tk.Text(self.window, font=('Arial', 12), width=85, height=20)
        self.text1.pack()
        # 两个控件关联
        scroll.config(command=self.text1.yview)
        self.text1.config(yscrollcommand=scroll.set)

        """定义按钮1，绑定触发事件方法"""
        """即登录按钮，当点击时将执行parse_hit_click_1方法。在真实使用场景中"""
        """parse_hit_click_1中可替换为自己写的真正登录函数。这里仅为示例"""
        self.button_1 = tk.Button(self.window, text='运行，GO LOVE', font=('Arial', 12), width=15, height=1, command=self.thread_run_2)
        self.button_1.pack(before=self.text1)

        """定义按钮2，绑定触发事件方法"""
        self.button_2 = tk.Button(self.window, text='清除', font=('Arial', 12), width=10, height=1, command=self.parse_hit_click_2)
        self.button_2.pack(anchor="e")

        url = 'http://www.ainicr.cn/tab/'
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36'
        }
        response = session.get(url, headers=headers).html
        self.result_data = response.xpath('/html/body/div[4]/div[1]/div[2]/ul/li/ul/li/a/text()')
        self.url_list = response.xpath('/html/body/div[4]/div[1]/div[2]/ul/li/ul/li/a/@href')
        text_list = list(filter(None, self.result_data))
        dict_data = {}
        self.big_data_dict = {}
        for index, title in enumerate(text_list):
            dict_data[index] = title
            self.big_data_dict[index] = title
            if len(dict_data) == 4:
                key_list = dict_data.keys()
                value_list = dict_data.values()
                content = ''
                for key, value in zip(key_list, value_list):
                    content = content + f'{key}: {value}\t\t\t'
                self.text1.insert("insert", content + "\n")
                dict_data = {}

    def thread_go_love_title(self):
        Thread(target=self.get_love_title).start()

    def get_love_title(self):
        """
        获取情话标题
        :return:
        """
        url = 'http://www.ainicr.cn/tab/'
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36'
        }
        response = session.get(url, headers=headers).html
        self.result_data = response.xpath('/html/body/div[4]/div[1]/div[2]/ul/li/ul/li/a/text()')
        self.url_list = response.xpath('/html/body/div[4]/div[1]/div[2]/ul/li/ul/li/a/@href')
        text_list = list(filter(None, self.result_data))
        dict_data = {}
        self.big_data_dict = {}
        for index, title in enumerate(text_list):
            dict_data[index] = title
            self.big_data_dict[index] = title
            if len(dict_data) == 4:
                key_list = dict_data.keys()
                value_list = dict_data.values()
                content = ''
                for key, value in zip(key_list, value_list):
                    content = content + f'{key}: {value}\t\t\t'
                self.text1.insert("insert", content + "\n")
                dict_data = {}

    def thread_run_2(self):
        Thread(target=self.parse_hit_click_1).start()

    def parse_hit_click_1(self):
        """定义触发事件1, 将执行结果显示在文本框中"""
        try:
            list1 = ['牛逼', '阔以哦', '厉害了', '就悄悄的', '哈哈哈哈', '卧槽', '原来你还有这一手']
            user_name = int(self.entry_user.get())
            # 根据编号，取出value
            title = self.big_data_dict[user_name]
            self.text1.delete("1.0", "end")
            self.text1.insert("insert", f'{random.choice(list1)}----你选择的是----{title}----正在给你寻找中' + "\n\n")
            time.sleep(3)
            title_num = self.result_data.index(title)
            url = self.url_list[title_num]
            # printinfo = "您输入的用户名是{},密码是{}".format(user_name, pass_wd)
            # self.text1.insert("insert", printinfo + "\n")
        except:
            msgbox.showerror(title='输入错误', message='请根据提示重新输入！')
        else:
            """触发事件绑定执行方法"""
            self.parse_job_run(url)

    def parse_job_run(self, url):
        """爬虫任务函数"""
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36'
        }
        response = session.get(url, headers=headers).html
        url_list = response.xpath('/html/body/div[5]/div[1]/div[2]/div/div[2]/h4/a/@href')
        self.parse_url_list_request(url_list)
        # 报错提示
        # msgbox.showerror(title='错误', message='无效，请重新输入！')
        pass

    def parse_url_list_request(self, url_list):
        """
        遍历循环解析
        :param url_list: 地址列表
        :return:
        """
        for url in url_list:
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36'
            }
            response = session.get(url, headers=headers).html
            text_list = response.xpath('/html/body/div[5]/div[1]/div[2]/div[2]/div/a/p/text()')
            for text in text_list:
                self.text1.insert("insert", text + "\n\n\n")
                # gui界面滑动条自动下拉
                self.text1.see('insert')

    def parse_hit_click_2(self):
        """定义触发事件2，删除文本框中内容"""
        self.entry_user.delete(0, "end")
        self.text1.delete("1.0", "end")
        self.thread_go_love_title()

    def center(self):
        """创建窗口居中函数方法"""
        ws = self.window.winfo_screenwidth()
        hs = self.window.winfo_screenheight()
        x = int((ws / 2) - (800 / 2))
        y = int((hs / 2) - (600 / 2))
        self.window.geometry('{}x{}+{}+{}'.format(800, 600, x, y))

    def run_loop(self):
        """禁止修改窗体大小规格"""
        self.window.resizable(False, False)
        """窗口居中"""
        self.center()
        """窗口维持--持久化"""
        self.window.mainloop()


if __name__ == '__main__':
    t = TKSpider()
    t.run_loop()

















